<template>
  <div
    class="package"
    v-loading="loading"
    element-loading-text="文件上传中...."
  >
    <input
      type="button"
      class="reset"
      value="更新"
      @click="resetData"
      v-show="pkg.packageName != ''"
    />
    <input
      type="button"
      class="reset"
      value="重置"
      @click="resetData"
      v-show="pkg.packageName != ''"
    />
    <h3>{{ title }}</h3>
    <div>
      <label>{{ msg }}</label>
      <el-upload
        ref="upload"
        name="file"
        class="upload-demo"
        drag
        accept=".apk"
        v-show="pkg.packageName == ''"
        v-bind:action="uploadUrl"
        multiple
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :before-upload="beforeUpload"
    
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将APK文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">只能上传APK,不超过200MB</div>
      </el-upload>
      <!-- <upload/> -->
    </div>

    <el-upload
      v-show="pkg.packageName != ''"
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>

    <div class="detail">
      <div class="base block">
        <span>基础信息</span>
        <ul class="list">
          <li class="item">
            <span class="name">包名</span>
            <input type="text" class="txt-val" v-model="pkg.packageName" />
          </li>
          <li class="item">
            <span class="name">应用名</span>
            <input type="text" class="txt-val" v-model="pkg.label" />
          </li>
          <li class="item">
            <span class="name">主Activity</span>
            <input type="text" class="txt-val" v-model="pkg.mainActivity" />
          </li>
          <li class="item">
            <span class="name">Application</span>
            <input type="text" class="txt-val" v-model="pkg.application" />
          </li>
          <li class="item">
            <span class="name">版本号</span>
            <input type="text" class="txt-val" v-model="pkg.versionCode" />
          </li>
          <li class="item">
            <span class="name">版本名</span>
            <input type="text" class="txt-val" v-model="pkg.versionName" />
          </li>
          <li class="item">
            <span class="name">compileSdkVersion</span>
            <input
              type="text"
              class="txt-val"
              v-model="pkg.compileSdkVersion"
            />
          </li>
          <li class="item">
            <span class="name">ICON</span>
            <input type="text" class="txt-val" v-model="pkg.icon" />
          </li>
          <li class="item">
            <span class="name">platformBuildVersionCode</span>
            <input
              type="text"
              class="txt-val"
              v-model="pkg.platformBuildVersionCode"
            />
          </li>
          <li class="item">
            <span class="name">是否可被调试</span>
            <input type="text" class="txt-val" v-model="pkg.debuggable" />
          </li>
        </ul>
      </div>
      <div class="banana block">
        <span>SDK信息</span>
        <ul
          class="list"
          v-if="pkg.bananaInfo != null && pkg.bananaInfo.sdkVersion > -1"
        >
          <li class="item">
            <span class="name">SDK版本</span>
            <input
              type="text"
              class="txt-val"
              v-if="pkg.bananaInfo.sdkVersion == 0"
              value="Demo包或者原包"
            />
            <input
              type="text"
              class="txt-val"
              v-else
              v-model="pkg.bananaInfo.sdkVersion"
            />
          </li>
          <li class="item">
            <span class="name">渠道</span>
            <input
              type="text"
              class="txt-val"
              v-model="pkg.bananaInfo.channel"
            />
          </li>
          <li class="item">
            <span class="name"
              >友盟Key
              <span class="um-type" v-if="pkg.bananaInfo.umType == 1"
                >(宿主)</span
              >
              <span class="um-type" v-else-if="pkg.bananaInfo.umType == 2"
                >(SDK_2.0)</span
              >
            </span>
            <input type="text" class="txt-val" v-model="pkg.bananaInfo.umKey" />
          </li>
          <li class="item">
            <span class="name">头条Key</span>
            <input
              type="text"
              class="txt-val"
              v-model="pkg.bananaInfo.bytedanceKey"
            />
          </li>
          <li class="item">
            <span class="name">快手Key</span>
            <input
              type="text"
              class="txt-val"
              v-model="pkg.bananaInfo.kuaishowKey"
            />
          </li>
          <li class="item">
            <span class="name">数据包</span>
            <input
              type="text"
              class="txt-val"
              v-model="pkg.bananaInfo.dataName"
            />
          </li>
          <li class="item">
            <span class="name">数据包大小</span>
            <input
              type="text"
              class="txt-val"
              v-model="pkg.bananaInfo.obbSize"
            />
          </li>
          <li class="item">
            <span class="name">启动Activity</span>
            <input
              type="text"
              class="txt-val"
              v-model="pkg.bananaInfo.launch"
            />
          </li>
        </ul>
        <p class="tip" v-else>没有集成SDK</p>
      </div>
      <div class="inner block">
        <span>宿主信息</span>
        <ul
          class="list"
          v-if="
            pkg.innerByteDanceInfo != null &&
            pkg.innerByteDanceInfo.config.mode != -1
          "
        >
          <li class="item">
            <span class="name">模式</span>
            <input
              type="text"
              class="txt-val"
              v-model="pkg.innerByteDanceInfo.config.mode"
            />
          </li>
          <li class="item">
            <span class="name">归因id</span>
            <input
              type="text"
              class="txt-val"
              v-model="pkg.innerByteDanceInfo.config.track_id"
            />
          </li>
          <li class="item">
            <span class="name">自动启动banner</span>
            <input
              type="text"
              class="txt-val"
              v-model="pkg.innerByteDanceInfo.config.banner_auto"
            />
          </li>
          <li class="item">
            <span class="name">Debug模式</span>
            <input
              type="text"
              class="txt-val"
              v-model="pkg.innerByteDanceInfo.config.debug"
            />
          </li>
          <li class="item">
            <span class="name">渠道</span>
            <input
              type="text"
              class="txt-val"
              v-model="pkg.innerByteDanceInfo.ads.remote.channel"
            />
          </li>
          <li class="item">
            <span class="name">应用名</span>
            <input
              type="text"
              class="txt-val"
              v-model="pkg.innerByteDanceInfo.config.app_name"
            />
          </li>
        </ul>
        <p class="tip" v-else>没有宿主头条</p>
      </div>
      <div class="permissions block">
        <span>权限信息</span>
        <ul class="list">
          <li
            v-for="(item, index) in pkg.permissions"
            :key="item"
            v-bind:class="index % 2 == 0 ? 'color-li' : ''"
          >
            <span class="name" v-if="index % 2 == 0">{{ item }}</span>
            <span class="dark-li" v-else>{{ item }}</span>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
// import upload from './Upload.vue'
import SparkMD5 from "spark-md5";
export default {
  name: "PackageInfo",
  // components: {
  //     upload
  // },
  props: {
    msg: String,
    count: Number,
    baseData: Object,
  },
  data: function () {
    return {
      loading: false,
      title: "获取APK信息",
      apkInfoUrl: this.$Global.host + "/banana/apk-info",
      uploadUrl: this.$Global.host + "/banana/upload",
      fileUrl: this.$Global.host + "/banana/file",
      imageUrl: "",
      pkg: {
        label: "",
        packageName: "",
        icon: "",
        versionCode: "",
        versionName: "",
        mainActivity: "",
        application: "",
        compileSdkVersion: "",
        platformBuildVersionCode: "",
        debuggable: "",
        permissions: [],
        bananaInfo: {
          bytedanceKey: "",
          channel: "",
          dataName: "",
          kuaishowKey: "",
          launch: "",
          obbSize: "",
          sdkVersion: "-1",
          umKey: "",
          umType: 0,
        },
        innerByteDanceInfo: {
          ads: {
            local: {
              appid: "5040889",
              banner: [],
              fullvideo: ["941629344"],
              insert: [],
              native_banner: [],
              native_express_banner: ["941629342"],
              native_express_insert: ["937171552"],
              native_insert: ["901121435"],
              rewardvideo: ["941629345"],
              splash: ["887287110"],
            },
            remote: {
              channel: "",
              city: "",
              country: "",
              packagename: "",
              platform: 2,
              province: "",
              version: "",
            },
          },
          config: {
            app_name: "",
            banner_auto: true,
            debug: false,
            mode: "-1",
            track: true,
            track_id: "",
          },
        },
      },
    };
  },
  methods: {
    resetData: function () {
      Object.assign(this.$data.pkg, this.$options.data().pkg);
    },
    uploadSuccess: function (response, file, fileList) {
      console.log("Upload complete!" + JSON.stringify(response));
      console.log(fileList);
      this.loading = false;
      
      this.getApkInfo(response.data);
    },
    uploadError: function (err, file, fileList) {
      console.log("error: " + err + file);
      console.log(fileList);
      this.loading = false;
      this.showMsg(err);
    },
    beforeUpload: function () {
      this.loading = true;
    },
    handleFileChange: function (file) {
      this.getFileMD5(file.raw).then( md5 => {
        this.$http.get(this.fileUrl, { params: { md5: md5 } }).then(
          function (resp) {
            if(resp.body.data ===''){
              console.log("文件不存在，现在上传！")
              this.$refs.upload.submit()
            }else{
              console.log(resp.body.data)
              this.getApkInfo(md5)
              
            }
          },
          function (err) {
            console.log(err);
          }
        );
      });
    },
    getFileMD5: function (file) {
      return new Promise((resolve, reject) => {
        var blobSlice =
            File.prototype.slice ||
            File.prototype.mozSlice ||
            File.prototype.webkitSlice,
          chunkSize = 2097152, // Read in chunks of 2MB
          chunks = Math.ceil(file.size / chunkSize),
          currentChunk = 0,
          spark = new SparkMD5.ArrayBuffer(),
          fileReader = new FileReader();

        fileReader.onload = function (e) {
          console.log("read chunk nr", currentChunk + 1, "of", chunks);
          spark.append(e.target.result); // Append array buffer
          currentChunk++;

          if (currentChunk < chunks) {
            loadNext();
          } else {
            var md5 = spark.end();
            console.log("finished loading");
            console.info("computed hash", md5); // Compute hash
            resolve(md5)
            console.log(reject)
          }
        };

        fileReader.onerror = function () {
          console.warn("oops, something went wrong.");
        };

        function loadNext() {
          var start = currentChunk * chunkSize,
            end =
              start + chunkSize >= file.size ? file.size : start + chunkSize;
          fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
        }

        loadNext();
      });
    },
    // uploadProgress: function (event, file, fileList) {
    //   console.log(file);
    //   console.log(fileList);
    // },
    getApkInfo: function (fileMD5) {
      this.$http.get(this.apkInfoUrl, { params: { md5: fileMD5 } }).then(
        function (resp) {
          this.pkg = resp.body.data;
          this.showTip("解析完成🚀");
          console.log("pkg: " + JSON.stringify(this.pkg));
        },
        function (err) {
          console.log(err);
        }
      );
    },
    showMsg: function (msg) {
      this.$alert("上传错误!" + msg, "提示", {
        confirmButtonText: "确定",
        callback: (action) => {
          this.$message({
            type: "info",
            message: `action: ${action}`,
          });
        },
      });
    },
    showTip: function (msg) {
      const h = this.$createElement;

      this.$notify({
        title: "通知😛",
        message: h("i", { style: "color: teal" }, msg),
      });
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
input {
  outline-style: none;
  border-style: solid;
  border-width: 0px 0px 1px 0px;
}
.package {
  text-align: center;
}
.reset {
  padding: 8px;
  background: #23c0b3;
  border-radius: 25px;
  font-size: 1.5rem;
  transition-property: background-color, font-size, color;
  transition-duration: 0.5s;
  transition-timing-function: ease-out;
}
.reset:hover {
  color: #d81818;
  background-color: #0f8076;
  font-size: 2rem;
  cursor: pointer;
}
.list {
  text-align: left;
}
.item {
  /* width: 250px; */
  padding-top: 10px;
}
.item input {
  width: 100%;
}
.name {
  display: inline-block;
  width: 200px;
}
.um-type {
  color: #d81818;
  font-weight: bold;
}
.txt-val {
  padding: 5px 1px;
  color: #198f71;
  font-size: 1.1rem;
}
.permissions ul {
  list-style-type: circle;
}
.permissions ul li {
  display: block;
  padding: 5px 5px;
}
.tip {
  font-size: 1.5rem;
  padding: 5px;
  color: rgb(190, 85, 85);
  background: #23c0b3;
}
.block {
  margin: 5px;
  padding: 2px;
  border: solid 1px #23c0b3;
}
.block > span {
  font-size: 1.2rem;
  font-weight: bold;
}
.color-li {
  background: #bdddda;
  display: inline-block;
}

/* 头像上传 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>